﻿namespace Samples.DiscoveryServices.ConsoleHost
{
    using ServiceContracts.Implementations;
    using System;
    using System.Configuration;
    using System.IO;
    using System.ServiceModel;
    using System.ServiceModel.Configuration;
    using HostConfiguration = System.Configuration.Configuration;

    /// <summary>
    ///     自定义的服务宿主程序。
    /// </summary>
    /// <remarks>
    ///     密闭的，不可从此类型继承。
    /// </remarks>
    public sealed class CustomizedServiceHost : ServiceHost
    {
        #region Private Data Members

        /// <summary>
        ///     私有的配置对象。
        /// </summary>
        private HostConfiguration hostConfiguration;

        #endregion Private Data Members

        #region Constructors

        /// <summary>
        ///     用于初始化一个 <see cref="CustomizedServiceHost"/> 类型的对象实例。
        /// </summary>
        public CustomizedServiceHost() : base(typeof(SimplestFeaturesServiceProvider))
        {
        }

        #endregion Constructors

        #region Protected Override Methods

        /// <summary>
        ///     加载配置文件的服务描述,它适用于运行时被构造。
        /// </summary>
        protected override void ApplyConfiguration()
        {
            base.LoadConfigurationSection(GetServiceConfiguration());
        }

        #endregion Protected Override Methods

        #region Private Methods

        /// <summary>
        ///     从私有配置文件Host.config加载<see cref="HostConfiguration"/>对象。
        /// </summary>
        /// <returns>
        ///     <see cref="HostConfiguration"/>对象实例。
        /// </returns>
        private HostConfiguration LoadHostConfiguration()
        {
            ExeConfigurationFileMap configurationFileMap = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Host.config")
            };
            return ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, ConfigurationUserLevel.None);
        }

        /// <summary>
        ///     获取服务配置节点。
        /// </summary>
        /// <returns>
        ///     <see cref="ServiceElement"/>对象实例。
        /// </returns>
        private ServiceElement GetServiceConfiguration()
        {
            HostConfiguration configuration = LoadHostConfiguration();
            ServiceModelSectionGroup serviceConfigGroup = configuration.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;
            return serviceConfigGroup.Services.Services["Samples.DiscoveryServices.ServiceContracts.Implementations.SimplestFeaturesServiceProvider"];
        }

        #endregion Private Methods
    }
}